package business

import (
	"fcs-api/src/app/model"
	"sort"
	"time"
)

// CreateLayer 创建一个层
func CreateLayer(layer *model.Layer) (*model.Layer, error) {
	if _, err := model.CreateLayer(layer); err != nil {
		_ = logger.Error("CreateAlias: insert alias db error, %v", err)
		return nil, err
	}
	return layer, nil
}

// GetLayerList 获取每个层最新版本列表
func GetLayerList(query *model.LayerListQuery) (*model.LayerListResult, error) {
	layerList, err := model.GetLayerList(query)
	if err != nil {
		_ = logger.Error("GetLayerList: get list from db error, %s", err.Error())
		return nil, err
	}
	layerCount, err := model.GetLayerListCount(query)
	if err != nil {
		_ = logger.Error("GetLayerList: get list count from db error, %s", err.Error())
		return nil, err
	}
	return &model.LayerListResult{
		TotalCount:      int(layerCount),
		RecordsFiltered: len(layerList),
		Result:          layerList,
	}, nil
}

// 获取一个层的所有版本
func GetLayerVersionList(rootId string) (*model.LayerVersionListResult, error) {
	layerList, err := model.GetLayerVersionList(rootId)
	if err != nil {
		_ = logger.Error("GetLayerVersionList: get list from db error, %s", err.Error())
		return nil, err
	}
	result := &model.LayerVersionListResult{}
	if len(layerList) != 0 {
		result.VersionList = layerList
		result.LayerName = layerList[0].Name
		result.LayerId = layerList[0].RootId
		result.RegionCode = layerList[0].RegionCode
		result.RegionName = layerList[0].RegionName
	}
	return result, nil
}

// GetLayerRuntimeList 获取匹配runtime的所有层
func GetLayerRuntimeList(uid, runtime string) ([]*model.LayerVersionList, error) {
	layerList, err := model.GetLayerByRuntime(uid, runtime)
	if err != nil {
		_ = logger.Error("GetLayerRuntimeList: get list from db error, %s", err.Error())
		return nil, err
	}
	layerMap := make(map[string]*model.LayerVersionList)
	for _, layer := range layerList {
		if versionList, ok := layerMap[layer.RootId]; ok {
			versionList.Versions = append(versionList.Versions, layer)
		} else {
			versionList = &model.LayerVersionList{
				LayerId:    layer.RootId,
				LayerName:  layer.Name,
				Versions:   make([]*model.Layer, 0),
				UpdateTime: layer.UpdateTime,
			}
			versionList.Versions = append(versionList.Versions, layer)
			layerMap[layer.RootId] = versionList
		}
	}
	result := make([]*model.LayerVersionList, 0, len(layerMap))
	for _, versionList := range layerMap {
		result = append(result, versionList)
	}
	sort.Slice(result, func(i, j int) bool {
		return time.Time(result[i].UpdateTime).After(time.Time(result[j].UpdateTime))
	})
	return result, nil
}

// DeleteLayerVersion 删除层版本
func DeleteLayerVersion(rootId, version string) error {
	_, err := model.DeleteLayerVersion(rootId, version)
	if err != nil {
		_ = logger.Error("DeleteLayerVersion: delete version from db error, %s", err.Error())
		return err
	}
	return nil
}
